#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import json
import uuid
from datetime import datetime
import shutil

def generate_random_id():
    return uuid.uuid4().hex + uuid.uuid4().hex

def generate_uuid():
    return str(uuid.uuid4())

def backup_file(file_path):
    if os.path.exists(file_path):
        backup_path = f"{file_path}.backup_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
        shutil.copy2(file_path, backup_path)
        print(f"[备份] 已创建备份文件: {backup_path}")

def update_storage_file(path):
    machine_id = generate_random_id()
    mac_id = generate_random_id()
    dev_id = generate_uuid()
    sqm_id = '{' + str(uuid.uuid4()).upper() + '}'

    backup_file(path)

    if os.path.exists(path):
        try:
            with open(path, 'r') as f:
                data = json.load(f)
        except Exception:
            data = {}
    else:
        data = {}

    data['telemetry.machineId'] = machine_id
    data['telemetry.macMachineId'] = mac_id
    data['telemetry.devDeviceId'] = dev_id
    data['telemetry.sqmId'] = sqm_id

    with open(path, 'w') as f:
        json.dump(data, f, indent=4)

    print("[✔] 已更新 storage.json 中的 ID")
    return machine_id

def update_machineid_file(path, machine_id):
    backup_file(path)
    with open(path, 'w') as f:
        f.write(machine_id)
    print("[✔] 已更新 machineid 文件")

def main():
    user_home = os.environ.get('USERPROFILE', '')
    base_path = os.path.join(user_home, 'AppData', 'Roaming', 'Cursor')
    storage_path = os.path.join(base_path, 'User', 'globalStorage', 'storage.json')
    machineid_path = os.path.join(base_path, 'machineid')

    print(f"[*] Storage 路径: {storage_path}")
    print(f"[*] MachineID 路径: {machineid_path}")

    machine_id = update_storage_file(storage_path)
    update_machineid_file(machineid_path, machine_id)

    print("\n[完成] 所有 ID 已成功更新 🎉")

if __name__ == '__main__':
    main()
